package com.gitee.feizns.dynamic.decrypt;

import lombok.Getter;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * RSA密钥对
 * <p>
 *     RSA公钥私钥对
 * </p>
 * @author feizns
 * @since 2023/2/1
 */
public class KeyPair {

    /**
     * @see java.security.KeyPair
     */
    @Getter
    private final java.security.KeyPair keyPair;

    /**
     * @param keyPair {@link java.security.KeyPair}
     */
    public KeyPair(java.security.KeyPair keyPair) {
        this.keyPair = keyPair;
    }

    /**
     * 获取将公钥进行base64编码之后的字符串
     * @return base64格式公钥
     */
    public String getBase64PublicKey() {
        return new String(Encrypts.base64Encode(keyPair.getPublic().getEncoded()));
    }

    /**
     * 获取将私钥进行base64编码之后的字符串
     * @return base64格式私钥
     */
    public String getBase64PrivateKey() {
        return new String(Encrypts.base64Encode(keyPair.getPrivate().getEncoded()));
    }

    /**
     * @return {@link PublicKey}
     */
    public PublicKey toPublicKey() {
        return keyPair.getPublic();
    }

    /**
     * @see PrivateKey
     * @return {@link PrivateKey}
     */
    public PrivateKey toPrivateKey() {
        return keyPair.getPrivate();
    }

    /**
     * @see Object#toString()
     * @return {@link String}
     */
    @Override
    public String toString() {
        return "publicKey:" + getBase64PublicKey() + "\n" +
               "privateKey:" + getBase64PrivateKey();
    }

}
